package com.luojialong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luojialong.enums.AffairStatus;
import com.luojialong.exception.AffairException;
import com.luojialong.model.domain.User;
import com.luojialong.model.request.user.UserQueryRequest;
import com.luojialong.model.request.user.UserRegisterRequest;
import com.luojialong.model.vo.user.UserVo;
import com.luojialong.service.UserService;
import com.luojialong.mapper.UserMapper;
import com.luojialong.utils.MyStringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

import static com.luojialong.constant.UserRank.USER_LOGIN_KEY;

/**
 * @author 罗家龙
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-04-21 15:30:01
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;


    /**
     * 用户注册
     * @param userRegisterRequest用户注册的请求
     * @return 新建用户的id
     */
    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckUserPassword();
        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号或密码,校验密码为空");
        }
        if (userAccount.length() < 8) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号的长度不得小于8");
        }
        if (userPassword.length() < 10 || userPassword.length() > 18 || checkPassword.length() < 10) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "密码长度不得小于10,且不得大于18");
        }
        String rule = "^(?![a-zA-Z]+$)(?!\\d+$)(?![^\\da-zA-Z\\s]+$).{10,18}$";
        if (!userPassword.matches(rule)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "密码必须包括数字,或字母,特殊符号,其中的两种组成");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "两次输入的密码都不一致");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "该账号已经存在了");
        }
        User addUser = new User();
        BeanUtils.copyProperties(userRegisterRequest,addUser);
        String md5Password = DigestUtils.md5DigestAsHex((userAccount + userPassword).getBytes(StandardCharsets.UTF_8));
        addUser.setUserAccount(userAccount);
        addUser.setUserPassword(md5Password);
        boolean save = this.save(addUser);
        if (!save) {
            throw new AffairException(AffairStatus.FAILURE, "注册失败,系统内部问题");
        }
        return addUser.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount  用户的账号
     * @param userPassword 用户密码
     * @return 返回脱敏后的用户信息
     */
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            //修改为自定义异常
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号或密码为空");
        }
        if (userAccount.length() < 8) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "账号的长度不得小于8");
        }
        if (userPassword.length() < 10 || userPassword.length() > 18) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "密码长度不得小于10,且不得大于18");
        }
        String rule = "^(?![a-zA-Z]+$)(?!\\d+$)(?![^\\da-zA-Z\\s]+$).{9,18}$";
        if (!userPassword.matches(rule)) {
            throw new AffairException(AffairStatus.PARAMS_ERROR, "密码必须包括数字,或字母,特殊符号,其中的两种组成");
        }
        String md5Password = DigestUtils.md5DigestAsHex((userAccount + userPassword).getBytes(StandardCharsets.UTF_8));
        QueryWrapper<User> userLoginWrapper = new QueryWrapper<>();
        userLoginWrapper.eq("userAccount", userAccount);
        userLoginWrapper.eq("userPassword", md5Password);
        User loginUser = this.getOne(userLoginWrapper);
        if (loginUser == null) {
            log.info("user login failed : userAccount or userPassword is error");
            throw new AffairException(AffairStatus.PARAMS_ERROR, "登录失败用户,账号或密码不匹配");
        }
        request.getSession().setAttribute(USER_LOGIN_KEY, loginUser);
        return loginUser;
    }


    /**
     * 用户注销
     *
     * @param request 请求
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_KEY);
        return 1;
    }

    /**
     * 获取已经登录的用户信息
     *
     * @param request 请求
     * @return 返回已经登录的用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(USER_LOGIN_KEY);
    }

    /**
     * 根据请求条件获得用户信息
     * @param queryRequest 用户的查询请求
     * @return 返回用户的查询条件器
     */
    @Override
    public QueryWrapper<User> getPageQueryWrapper(UserQueryRequest queryRequest) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();
        MyStringUtils.setWrapper(userQueryWrapper,sortField,sortOrder);
        String username = queryRequest.getUsername();
        String phone = queryRequest.getPhone();
        String email = queryRequest.getEmail();
        String major = queryRequest.getMajor();
        String school = queryRequest.getSchool();
        if (StringUtils.isNotBlank(username)){
            userQueryWrapper.like("username",username);
        }
        if (StringUtils.isNotBlank(phone)) {
            userQueryWrapper.eq("phone",phone);
        }
        if (StringUtils.isNotBlank(email)) {
            userQueryWrapper.eq("major",major);
        }
        if (StringUtils.isNotBlank(school)) {
            userQueryWrapper.eq("school",school);
        }
        return userQueryWrapper;
    }



    /**
     * 根据用户的页面对象,转化成视图层的用户页面对象
     * @param userPage 用户完整的信息页面
     * @return 返回视图层用户信息
     */
    @Override
    public Page<UserVo> getPageVo(Page<User> userPage) {
        List<User> records = userPage.getRecords();
        List<UserVo> userVoList = records.stream().map(UserVo::transferVo).collect(Collectors.toList());
        Page<UserVo> userVoPage = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        userVoPage.setRecords(userVoList);
        return userVoPage;
    }


}




